package com.lvyq.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lvyq.cache.CacheManager;
import com.lvyq.manager.MyX509TrustManager;
import com.lvyq.model.apiinfo.ApiInfo;
import lombok.extern.java.Log;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: weg
 * @description:快递查询
 * @author: lvyq
 * @create: 2023-04-17 13:52
 **/
@Log
public class ExpressQueryUtils {

    public static String  getExpressInfo(ApiInfo apiInfo,String num){
      String result="";
      String val =CacheManager.get(num);
      if (val!=null ){
            //数据已存在
            result=val;
        }else {
            String data="";
            if (num.startsWith("YT")){
                data=getYuanTongDate(apiInfo,num);
            }
            result =getInfo(data,num);
        }
        return result;
    }



    /** 
    * @Description: 圆通数据
     * @param num
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/4/18 17:18
    */
    public static String getYuanTongDate(ApiInfo apiInfo,String num){
        //设置请求链接
        String path =apiInfo.getToken().replace("{num}",num);
        String url = apiInfo.getUrl()+path;
        //发送请求
        String res= sendGet(url,path);
        //转换  获取的是个unicode 需要解码
        res=unicodeDecode(res);
        res=res.substring(26,res.length()-1);
        return res;
    }


    /** 
    * @Description: 获取数据
     * @param result
    * @return: 
    * @Author: lvyq
    * @Date: 2023/4/17 16:03
    */
    private static String getInfo(String result,String key) {
        JSONObject data= JSONObject.parseObject(result).getJSONObject("data");
        //快递名称
        String title="";
        try{
            title =data.getJSONObject("source").getString("name");
        }catch (Exception e){
            title =data.getJSONObject("officalService").getString("comName");
        }
        JSONArray array =data.getJSONArray("context");
         StringBuffer stringBuffer = new StringBuffer();
         stringBuffer.append("           \uD83D\uDE9A"+title+"\uD83D\uDE9A\n");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < array.size(); i++) {
            JSONObject jsonObject = array.getJSONObject(i);
            String time = jsonObject.getString("time");
            long lt = new Long(time);
            Date date = new Date(lt*1000L);
            time = format.format(date);
            String desc =jsonObject.getString("desc");
            stringBuffer.append("⏰"+time+"\n");
            stringBuffer.append("\uD83D\uDCDD"+desc+"\n");
           // stringBuffer.append("━━━━━━━\uD83D\uDCCE━━━━━━━\n");
        }
        String res = "暂未查询到相关快递信息";
        res=stringBuffer.toString();
        CacheManager.set(key,res,60*1000*60*3);
        return res;

    }

    public static String sendGet(String url,String path) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            java.net.URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("authority","express.baidu.com");
            connection.setRequestProperty("method","GET");
            connection.setRequestProperty("path",path);
            //Cookie 设置
            connection.setRequestProperty("Cookie","BIDUPSID=BE2DDA6E88C38391D319B4B621400B81; PSTM=1651301665; BAIDUID=BE2DDA6E88C383917969F003CF31DDBB:FG=1; BDUSS=09wWkUtVWJDTmJ-Y0lqM0g0MmQ0WFRQMU55eWNzSWFYcjdTejhzRmItVGVRR0JrRVFBQUFBJCQAAAAAAAAAAAEAAADDfxJ0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN6zOGTeszhkR; BDUSS_BFESS=09wWkUtVWJDTmJ-Y0lqM0g0MmQ0WFRQMU55eWNzSWFYcjdTejhzRmItVGVRR0JrRVFBQUFBJCQAAAAAAAAAAAEAAADDfxJ0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN6zOGTeszhkR; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; H_PS_PSSID=26350; BAIDUID_BFESS=BE2DDA6E88C383917969F003CF31DDBB:FG=1; PSINO=2; delPer=0; BA_HECTOR=a124042haga02l8k200g203c1i417561m; ZFY=YPNSt6eaktVtywMFRbOFmN9l9hTtIPFNj66n:A9:AUkys:C; BDRCVFR[2LwUDnnf6gt]=byihNP1e9wDIgNdmhf8mvqV");
            connection.connect();
            Map<String, List<String>> map = connection.getHeaderFields();
            Iterator var8 = map.keySet().iterator();

            while(var8.hasNext()) {
                String key = (String)var8.next();
            }
            String line;
            for(in = new BufferedReader(new InputStreamReader(connection.getInputStream())); (line = in.readLine()) != null; result = result + line) {
            }
        } catch (Exception var18) {
            System.out.println("发送GET请求出现异常！" + var18);
            var18.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception var17) {
                var17.printStackTrace();
            }

        }
        return result;
    }


    /**
     * @param string
     * @return 转换之后的内容
     * @Title: unicodeDecode
     * @Description: unicode解码 将Unicode的编码转换为中文
     */
    public static String unicodeDecode(String string) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(string);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            string = string.replace(matcher.group(1), ch + "");
        }
        return string;
    }

}
